package org.example.task;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import org.example.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.ConnectException;

public class HttpTask implements ISimpleTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpTask.class);

    private RestTemplate restTemplate;
    private String url;
    private String params;
    private Result<String> taskResult;

    public HttpTask(String url) {
        this.url = url;
        initBean();
    }

    public HttpTask(String url, String params) {
        this.url = url;
        this.params = HexUtil.encodeHexStr(params, CharsetUtil.CHARSET_UTF_8);
        initBean();
    }

    private void initBean() {
        restTemplate = SpringUtil.getBean(RestTemplate.class);
    }

    @Override
    public Result<String> execute() {
        Result<String> result = null;
        try {
            this.url = StrUtil.isBlank(this.params) == true ? this.url : this.url + "?params=" + this.params;
            ResponseEntity<String> response = restTemplate.getForEntity(this.url, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                result = JSONObject.parseObject(response.getBody(), Result.class);
            } else {
                // 处理错误情况
                result = Result.error("服务端异常，请求失败");
            }
        } catch (Exception e) {
            result = Result.error("远程服务异常或者网络通信异常");
            LOGGER.error("远程服务异常或者网络通信异常.", e);
        }
        this.taskResult = result;
        LOGGER.info("HttpTask url:{}", this.url);
        return result;
    }

}
